//
//  QRCodeVC.swift
//  RPay
//
//  Created by Charlie Liao on 2017/7/5.
//  Copyright © 2017年 Charlie. All rights reserved.
//

import UIKit
import AVFoundation
import SnapKit

class QRCodeVC: BaseVC, AVCaptureMetadataOutputObjectsDelegate {
    
    // MARK: - Life Cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = LocalStr("扫一扫")
        // Do any additional setup after loading the view.
        
        
        // 摄像头 layer
        session.sessionPreset = AVCaptureSessionPreset1920x1080
        videoPreviewLayer = AVCaptureVideoPreviewLayer(session: session)
        videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
        videoPreviewLayer.backgroundColor = UIColor.appBackground.cgColor
        view.layer.addSublayer(videoPreviewLayer)
        
        // 蒙版 layer
        maskLayer.backgroundColor = UIColor.black.withAlphaComponent(0.4).cgColor
        view.layer.addSublayer(maskLayer)
        maskLayer.mask = maskShapeLayer
        
        //
        view.addSubview(scanImgView)
        scanImgView.snp.makeConstraints { (maker) in
            maker.centerX.equalToSuperview()
            maker.bottom.equalToSuperview().multipliedBy(320.7/603)
        }
        
        
        let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
        do {
            let input = try AVCaptureDeviceInput(device: captureDevice)
            if session.canAddInput(input) {
                session.addInput(input)
            } else {
                alert(LocalStr("摄像头不可用"))
                return
            }
            
        } catch {
            alert(LocalStr("摄像头不可用"))
            return
        }
        
        let metadataOutput = AVCaptureMetadataOutput()
        if session.canAddOutput(metadataOutput) {
            session.addOutput(metadataOutput)
            //        metadataOutput.rectOfInterest = CGRectMake
            metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
            metadataOutput.metadataObjectTypes = [
                AVMetadataObjectTypeQRCode,
                AVMetadataObjectTypeCode39Code,
                AVMetadataObjectTypeCode128Code,
                AVMetadataObjectTypeCode39Mod43Code,
                AVMetadataObjectTypeEAN13Code,
                AVMetadataObjectTypeEAN8Code,
                AVMetadataObjectTypeCode93Code]
        } else {
            alert(LocalStr("摄像头不可用"))
            return
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        videoPreviewLayer?.frame = view.layer.bounds
        maskLayer.frame = view.layer.bounds
        
        // 蒙版
        let path = UIBezierPath(roundedRect: view.layer.bounds, cornerRadius: 0)
        let path2 = UIBezierPath(roundedRect: scanImgView.frame, cornerRadius: 0).reversing()
        path.append(path2)
        maskShapeLayer.path = path.cgPath
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController!.setNavigationBarHidden(false, animated: animated)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if !session.isRunning {
            session.startRunning()
        }
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        if session.isRunning {
            session.stopRunning()
        }
    }
    
    // MARK: - AVCaptureMetadataOutputObjectsDelegate
    func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!)
    {
        if metadataObjects.count > 0 && navigationController != nil
        {
            let resultObj = metadataObjects.first as! AVMetadataMachineReadableCodeObject
            let resultStr = resultObj.stringValue!
            if !resultStr.isEmpty {
                // 先停二维码扫描
                session.stopRunning()
                // 播放音效和振动
                UIDevice.playEffect("QRcode_notice.caf")
                UIDevice.playVibrate()
                
                let components = resultStr.components(separatedBy: "|")
                
                if components.count == 3 { // 扫描到商品二维码
                    //商品二维码 12|牛肉|16.65
                    // 二维码第0位 商品id
                    let id = components[0]
                    // 检查是否为int型
                    if Int64(id) != nil {
                        
                        // 二维码第1位 商品名称
                        let name = components[1]
                        
                        // 二维码第2位 商品价格
                        let price = components[2]
                        // 是否为Double型，
                        if  Double(price) != nil {
                            let vc = ProductDetailVC()
                            vc.goods = GoodsModel(id: id, name: name, price: price)
                            navigationController!.pushViewController(vc, animated: true)
                            return
                        }
                    }
                    
                } else if components.count == 4 { // 扫描到收款二维码
                    // 转账二维码 twuser|30.00|1500889338|02
                    // 二维码第0位 username
                    let userName = components[0]
                    // 二维码第1位 转账金额
                    let money = components[1]
                    // 是否为Double型
                    if  Double(money) != nil {
                        //  二维码第2位 时间戳
                        let generaltime = components[2]
                        // 是否为long long 型
                        if Int64(generaltime) != nil {
                            //  二维码第3位 类型
                            let type = components[3]
                            // 收款二维码
                            if type == "02" {
                                let vc = PayAmountVC()
                                vc.userName = userName
                                vc.money = money
                                vc.generaltime = generaltime
                                navigationController!.pushViewController(vc, animated: true)
                                return
                            }
                        }
                    }
                }
                    
                else {
                    if let data = Data(base64Encoded: resultStr) {
                        if let data = (data as NSData).decryptDES(withKey: "Rpay2017") {
                            let codeStr = String( data: data, encoding: .utf8)
                            let components = codeStr!.components(separatedBy: "|")
                            
                            if components.count == 4 { // 扫描到付款二维码
                                // 转账二维码 twuser|30.00|1500889338|01
                                // 二维码第0位 username
                                let userName = components[0]
                                // 二维码第1位 转账金额
                                let money = components[1]
                                // 是否为Double型
                                if  Double(money) != nil {
                                    //  二维码第2位 时间戳
                                    let generaltime = components[2]
                                    // 是否为long long 型
                                    if Int64(generaltime) != nil {
                                        //  二维码第3位 类型
                                        let type = components[3]
                                        // 付款二维码
                                        if type == "01" {
                                            let vc = CollectionAmountVC()
                                            vc.userName = userName
                                            vc.generaltime = generaltime
                                            navigationController!.pushViewController(vc, animated: true)
                                            return
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                
                alert(LocalStr("二维码无效"))
                // 内容不正确，重新开启二维码扫描
                session.startRunning()
            }
        }
    }
    
    // MARK: - Get
    let session = AVCaptureSession()
    
    var videoPreviewLayer: AVCaptureVideoPreviewLayer!
    lazy var maskShapeLayer = CAShapeLayer()
    lazy var maskLayer = CALayer()
    
    var scanImgView: UIImageView = {
        let scanImgView = UIImageView(image: UIImage(named: "bg_saoyisao"))
        scanImgView.layer.borderWidth = 0.5
        scanImgView.layer.borderColor = UIColor.appTheme.cgColor
        return scanImgView
    }()
}
